<template>
  <div class="community-container">
    <div class="community-header">
      <h1>社区讨论</h1>
      <div class="header-actions">
        <router-link to="/post" v-if="isLoggedIn">
          <el-button type="primary">
            <el-icon><Plus /></el-icon> 发布帖子
          </el-button>
        </router-link>
        <el-button v-else type="primary" @click="goToLogin">
          <el-icon><Plus /></el-icon> 登录发帖
        </el-button>
      </div>
    </div>
    
    <div class="filter-bar">
      <div class="sort-options">
        <el-radio-group v-model="sortBy" @change="fetchPosts(1)">
          <el-radio-button label="latest">最新</el-radio-button>
          <el-radio-button label="popular">热门</el-radio-button>
        </el-radio-group>
      </div>
      
      <div class="category-filter">
        <el-select
          v-model="selectedCategory"
          placeholder="按分类筛选"
          clearable
          @change="fetchPosts(1)"
        >
          <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
          />
        </el-select>
      </div>

      <div class="tag-filter" v-if="hotTags.length > 0">
        <el-select
          v-model="selectedTag"
          placeholder="按话题筛选"
          clearable
          @change="fetchPosts(1)"
        >
          <el-option
            v-for="tag in hotTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <!-- 错误提示 -->
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    />
    
    <!-- 帖子列表 -->
    <div v-if="posts.length > 0 && !loading" class="posts-list">
      <div v-for="post in posts" :key="post._id" class="post-card" @click="viewPostDetail(post._id)">
        <div class="post-header">
          <div class="author-info">
            <el-avatar :src="post.user.avatar" :size="32">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="author-name">{{ post.user.username }}</span>
          </div>
          <div class="post-time">{{ formatDate(post.createdAt) }}</div>
        </div>
        
        <h2 class="post-title">{{ post.title }}</h2>
        
        <div class="post-preview">{{ truncateContent(post.content) }}</div>
        
        <div v-if="post.tags && post.tags.length > 0" class="post-tags">
          <el-tag 
            v-for="tag in post.tags" 
            :key="tag" 
            size="small" 
            effect="plain"
            class="tag-item"
            @click.stop
          >
            {{ tag }}
          </el-tag>
        </div>
        
        <div v-if="post.images && post.images.length > 0" class="post-images">
          <el-image 
            v-for="(image, index) in post.images.slice(0, 3)" 
            :key="index"
            :src="getImageUrl(image)" 
            fit="cover"
            class="post-image"
            @click.stop
          />
          <div v-if="post.images.length > 3" class="more-images">
            +{{ post.images.length - 3 }}
          </div>
        </div>
        
        <div class="post-stats">
          <span><el-icon><View /></el-icon> {{ post.views || 0 }}</span>
          <span><el-icon><ChatDotRound /></el-icon> {{ post.comments?.length || 0 }}</span>
          <span><el-icon><Star /></el-icon> {{ post.likes?.length || 0 }}</span>
        </div>
      </div>
    </div>
    
    <!-- 无数据提示 -->
    <el-empty 
      v-if="posts.length === 0 && !loading" 
      description="暂无帖子"
    >
      <template #extra>
        <router-link to="/post" v-if="isLoggedIn">
          <el-button type="primary">发布第一篇帖子</el-button>
        </router-link>
        <el-button v-else type="primary" @click="goToLogin">登录发帖</el-button>
      </template>
    </el-empty>
    
    <!-- 分页 -->
    <div v-if="totalPages > 1 && !loading" class="pagination">
      <el-pagination
        layout="prev, pager, next"
        :total="totalPosts"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Plus, View, ChatDotRound, Star } from '@element-plus/icons-vue'
import axios from '@/services/axios'

const router = useRouter()
const store = useStore()

// 引入 Category 服务
import * as categoryService from '@/services/categoryService';

// 状态变量
const posts = ref([])
const loading = ref(true)
const error = ref(null)
const currentPage = ref(1)
const totalPages = ref(1)
const totalPosts = ref(0)
const pageSize = ref(10)
const sortBy = ref('latest') // latest, popular
const selectedTag = ref('')
const selectedCategory = ref('')
const hotTags = ref([])
const categories = ref([])

// 计算属性
const isLoggedIn = computed(() => store.getters['auth/isAuthenticated'])

// 获取帖子列表
const fetchPosts = async (page = 1) => {
  loading.value = true
  error.value = null
  currentPage.value = page
  
  try {
    const params = {
      page: page,
      limit: pageSize.value,
      sort: sortBy.value
    }
    
    if (selectedTag.value) {
      params.tag = selectedTag.value
    }

    if (selectedCategory.value) {
      params.category = selectedCategory.value
    }
    
    const response = await axios.get('/api/posts', { params })
    posts.value = response.data.posts
    totalPages.value = response.data.totalPages
    totalPosts.value = response.data.totalPosts
  } catch (err) {
    console.error('获取帖子列表失败:', err)
    error.value = err.response?.data?.error || '获取帖子列表失败'
    posts.value = []
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await categoryService.getCategories();
    categories.value = response.data.map(cat => ({ label: cat.name, value: cat._id }));
  } catch (err) {
    console.error('获取分类列表失败:', err);
  }
};

// 获取热门标签
const fetchHotTags = async () => {
  try {
    const response = await axios.get('/api/topics/hot')
    hotTags.value = response.data
  } catch (err) {
    console.error('获取热门标签失败:', err)
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  fetchPosts(page)
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 查看帖子详情
const viewPostDetail = (postId) => {
  router.push(`/post/${postId}`)
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

// 截断内容
const truncateContent = (content) => {
  if (!content) return ''
  return content.length > 100 ? content.substring(0, 100) + '...' : content
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  const now = new Date()
  const diff = now - date
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  }
  
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  }
  
  // 大于30天，显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

onMounted(() => {
  fetchPosts()
  fetchHotTags()
  fetchCategories()
})

// 将相对路径转换为完整的图片 URL
const getImageUrl = (relativePath) => {
  if (!relativePath) return ''; // 如果没有路径，返回空字符串
  // 假设后端服务运行在 localhost:3000
  // 在生产环境中，应该使用配置的基础 URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'; 
  return `${baseUrl}${relativePath}`;
};
 </script>
 
 <style scoped>
.community-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.community-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.community-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.loading-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-size: 14px;
  color: #606266;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

.post-title {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.post-preview {
  margin-bottom: 16px;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.post-images {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  position: relative;
}

.post-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.more-images {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 16px;
  border-radius: 4px;
}

.post-stats {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 14px;
}

.post-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
</style>